package com.jinhua.batch.service;


import com.alibaba.excel.EasyExcel;
import com.jinhua.batch.constant.StageEnum;
import com.jinhua.batch.listener.ExcelHandleListener;
import com.jinhua.batch.model.BatchProcessRequest;
import com.jinhua.batch.model.ProgressVO;
import com.jinhua.batch.model.ResultItemVO;
import com.jinhua.batch.utils.ProgressUtil;
import com.jinhua.common.utils.JsonUtils;
import com.jinhua.cos.ScaffoldingCosSdkService;
import com.jinhua.exceptions.TRetailRuntimeException;
//import com.tencent.sr.rmall.springbootstarter.redis.RedisClient;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import javax.annotation.Resource;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Copyright
 *
 * @Author WuHuang
 * @Date 2023/3/31
 */


@Component
public class ExcelBatchService {
    private static final Logger log = LoggerFactory.getLogger(ExcelBatchService.class);
//    @Resource
//    private RedisClient redisClient;
    @Resource
    private ScaffoldingCosSdkService scaffoldingCosSdkService;
    @Resource
    private Executor uploadTaskExecutor;
    @Resource
    private DataHandleService dataHandleService;
    @Value("${env.global.cos.exportBucket}")
    private String exportBucket;

    public ExcelBatchService() {
    }

    public <T extends ResultItemVO> void batchProcessExcel(BatchProcessRequest<T> batchProcessRequest) {
        URL url = null;

        try {
            url = new URL(batchProcessRequest.getExcelUrl());
        } catch (MalformedURLException var10) {
            log.error(var10.getMessage(), var10);
        }

        String bucket = url.getHost().split("\\.")[0];
        String path = url.getPath();
        String fileKey = null;

        try {
            fileKey = URLDecoder.decode(path, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException var9) {
            log.error(var9.getMessage(), var9);
        }

        String[] value = fileKey.split("/");
        ProgressVO progressVO = new ProgressVO();
        progressVO.setTaskId(batchProcessRequest.getTaskId());
        progressVO.setCurrentStage(StageEnum.TO_BE_DISPATCH.getDesc());
        progressVO.setUploadFileUrl(batchProcessRequest.getExcelUrl());
        ProgressUtil.saveProgress(progressVO);
        String finalFileKey = fileKey;
        this.uploadTaskExecutor.execute(() -> {
            try {
                this.uploadUserPackageTask(batchProcessRequest, batchProcessRequest.getLineClass(), finalFileKey, bucket, batchProcessRequest.getExcelUrl(), batchProcessRequest.getTaskId());
            } catch (Exception var6) {
                progressVO.setTaskId(batchProcessRequest.getTaskId());
                progressVO.setCurrentStage(StageEnum.EXCEPTION_INTERRUPT.getDesc());
                progressVO.setCurrentStageProgressDetail(var6.getMessage());
                ProgressUtil.saveProgress(progressVO);
            }

        });
    }

    private <T extends ResultItemVO> void uploadUserPackageTask(BatchProcessRequest<T> batchProcessRequest, Class<T> lineClass, String fileKey, String bucket, String rawUrl, String taskId) {
        ProgressVO progressVO = new ProgressVO();
        progressVO.setTaskId(taskId);
        progressVO.setCurrentStage(StageEnum.TO_BE_DISPATCH.getDesc());
        progressVO.setUploadFileUrl(rawUrl);
        ProgressUtil.saveProgress(progressVO);

        try {
            log.info("开启下载文件，batchProcessRequest={}", JsonUtils.toString(batchProcessRequest));
            InputStream is = this.scaffoldingCosSdkService.downLoadFile(bucket, fileKey);
            log.info("下载文件完成，batchProcessRequest={}", JsonUtils.toString(batchProcessRequest));
            List<T> parseResultList = new ArrayList();
            log.info("开始解析文件，batchProcessRequest={}", JsonUtils.toString(batchProcessRequest));
            EasyExcel.read(is, lineClass, new ExcelHandleListener(parseResultList)).sheet().doRead();
            log.info("文件解析完成，batchProcessRequest={}，parseResultList={}", JsonUtils.toString(batchProcessRequest), JsonUtils.toString(parseResultList));
            this.dataHandleService.handleDataInExcel(batchProcessRequest, lineClass, parseResultList, taskId, rawUrl, this.exportBucket);
        } catch (Exception var10) {
            log.error("批量执行任务失败", var10);
            progressVO = ProgressUtil.queryTaskStatus(taskId);
            progressVO.setCurrentStage(StageEnum.EXCEPTION_INTERRUPT.getDesc());
            if (var10 instanceof TRetailRuntimeException) {
                progressVO.setCurrentStageProgressDetail(((TRetailRuntimeException)var10).getMessage());
            } else {
                progressVO.setCurrentStageProgressDetail(var10.getMessage() + ", " + ExceptionUtils.getStackTrace(var10));
            }

            ProgressUtil.saveProgress(progressVO);
        }

    }
}

